package jwt

import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

const (
	TokenExpire = time.Hour
)

var mySecret = []byte("jgfsdfajsk214f")


type MyClaims struct {
	UserId int64 `json:"user_id"`
	jwt.StandardClaims
}

// 生成token
func GenToken(userId int64) (string, error) {
	// 创建声明的数据
	c:=MyClaims{
		UserId: userId,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt:time.Now().Add(TokenExpire).UnixMilli(),
			Issuer: "bluebell",
		},
	}
	// 使用指定的签名方法创建签名对象
	token:=jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	// 使用secret签名并获得完整的编码后的字符串token
	return token.SignedString(mySecret)
}

func ParseToken(tokenString string) (*MyClaims, error) {
	var uc = new(MyClaims)
	token, err:=jwt.ParseWithClaims(tokenString, uc,
		func(token *jwt.Token) (interface{}, error) {
			return mySecret, nil
		},
	)
	fmt.Println(token)
	fmt.Println(uc)
	if err!=nil {
		return nil, err
	}
	if token.Valid {
		return uc, nil
	}
	return nil, errors.New("invalid token")
}